import React, {createContext, useContext, useState, ReactNode} from 'react';

type Faction = {
  id: string;
  name: string;
  color: string;
};

type Player = {
  id: string;
  name: string;
  faction: Faction;
  isCommander: boolean;
};

type GameState = {
  currentPlayer: Player | null;
  players: Player[];
  gamePhase: 'setup' | 'battle' | 'diplomacy' | 'ended';
  resources: {
    grain: number;
    horses: number;
    gunpowder: number;
    dragonVein: number;
  };
};

const GameContext = createContext<{
  state: GameState;
  dispatch: React.Dispatch<any>;
}>({
  state: {
    currentPlayer: null,
    players: [],
    gamePhase: 'setup',
    resources: {
      grain: 0,
      horses: 0,
      gunpowder: 0,
      dragonVein: 0,
    },
  },
  dispatch: () => null,
});

export const GameProvider = ({children}: {children: ReactNode}) => {
  const [state, setState] = useState<GameState>({
    currentPlayer: null,
    players: [],
    gamePhase: 'setup',
    resources: {
      grain: 0,
      horses: 0,
      gunpowder: 0,
      dragonVein: 0,
    },
  });

  return (
    <GameContext.Provider value={{state, dispatch: setState}}>
      {children}
    </GameContext.Provider>
  );
};

export const useGame = () => useContext(GameContext);
